# -*- coding: utf-8 -*-

from odoo.http import request

from odoo_contrib import http as contrib_http
from odoo_contrib.parser import parse_with
from odoo_contrib.marshal import marshal_with

from ..schemas import parser
from ..schemas import marshals
from ..utils.settings import Settings
from ..utils.exceptions import FrontendException


@contrib_http.route('/exhibition')
class ExhibitRepository(contrib_http.Controller):
    @contrib_http.route('/exhibit/', methods=['GET'])
    @parse_with(parser.exhibit.ExhibitRepositorySchema)
    @marshal_with(marshals.exhibit.ExhibitRepositorySchema, envelope='data')
    def exhibit_list(self):
        params = self.parser.parse()
        page = params['page']
        page_size = Settings().page_size
        enabled_only = params['enabled_only']
        categories = params['categories']
        q = params['q']

        domains = []
        if enabled_only:
            domains.append(('enabled', '=', True))
        if categories:
            domains.append(('categories', 'in', categories))
        if q:
            domains.extend(('|', ('name', 'ilike', q), ('code', 'ilike', q)))
        exhibits = request.env['exhibition.exhibit'].search(
            domains,
            offset=page_size * page,
            limit=page_size,
        )
        return {
            'entries': exhibits,
            'count': request.env['exhibition.exhibit'].search_count(domains),
        }


@contrib_http.route('/exhibition')
class ExhibitEntry(contrib_http.Controller):
    @contrib_http.route('/exhibit/entry/<int:eid>')
    @marshal_with(marshals.exhibit.ExhibitSchema, envelope='data')
    def exhibit_entry(self, eid):
        exhibit = request.env['exhibition.exhibit'].browse(eid)
        if not exhibit.exists():
            raise FrontendException(
                errcode=200301,
                params={
                    'exhibitId': eid,
                }
            )
        exhibit.been_viewed()
        exhibit.been_visited()
        # return exhibit.read()[0]
        return exhibit
